"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 导入导出支持M*特性
Case Name   : gs_basebackup备份兼容b库表及存储过程
Create At   : 2023.09.20
Owner       : z@wan005
Description :
    1、创建兼容b库数据库
    2、b库下查询dolphin插件
    3、创建备份目录并修改权限
    4、创建测试用户，测试表，存储过程
    5、执行basebackup
    6、查询表
    7、查询存储过程
    8、清理环境
Expect      :
    1、成功
    2、自动加载成功,无需手动创建
    3、成功
    4、成功
    5、成功
    6、成功
    7、成功
    8、成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

sh_primary = CommonSH('PrimaryDbUser')


@unittest.skipIf(2 > sh_primary.get_node_num(), '非1主2备环境不执行')
class ToolsTest33(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.common = Common()
        self.Constant = Constant()
        self.sh_sta1 = CommonSH('Standby1DbUser')
        self.sh_sta2 = CommonSH('Standby2DbUser')
        self.user_node = Node('PrimaryDbUser')
        self.back_path = os.path.join(os.path.dirname(macro.DB_INSTANCE_PATH),
                                      'tools_backup0033')
        self.db_name = 'db_backup_case0033'
        self.user_name = 'user_backup_case0033'
        self.tb_name = 'tb_backup_case0033'
        self.pro_name = 'pro_backup_case0033'

    def test_tinyblob(self):
        text = '-----step1:创建兼容b库数据库;expect:成功-----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"create database {self.db_name} " \
                  f"dbcompatibility ='B' encoding ='UTF8';"
        self.log.info(sql_cmd)
        sql_res = sh_primary.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('CREATE DATABASE', sql_res, '执行失败' + text)

        text = '-----step2:b库下查询dolphin插件;expect:自动加载成功,无需手动创建-----'
        self.log.info(text)
        sql_cmd = "select extname from pg_extension where extname ='dolphin';"
        self.log.info(sql_cmd)
        sql_res = sh_primary.execut_db_sql(sql_cmd, dbname=self.db_name)
        self.log.info(sql_res)
        self.assertIn('extname', sql_res, '查询失败')
        self.assertIn('dolphin', sql_res, '执行失败' + text)

        text = '-----step3:创建备份目录并修改权限;expect:成功-----'
        self.log.info(text)
        cmd = f"rm -rf {self.back_path};" \
              f"mkdir -p {self.back_path};" \
              f"chmod 700 {self.back_path};" \
              f"ls {os.path.dirname(macro.DB_INSTANCE_PATH)} | " \
              f"grep 'tools_backup0033';"
        self.log.info(cmd)
        res = self.common.get_sh_result(self.user_node, cmd)
        self.assertIn('tools_backup0033', res, '文件夹创建失败')

        text = '-----step4:创建测试用户，测试表，存储过程;expect:成功-----'
        self.log.info(text)
        sql = f'''drop user if exists {self.user_name};
        create user {self.user_name} password '{macro.COMMON_PASSWD}';
        drop table if exists {self.tb_name};
        create table {self.tb_name}(name varchar(100), loc varchar(100), \
        no integer);
        insert {self.tb_name} values('macrosoft', 'usa', 001);
        insert {self.tb_name} values('oracle', 'usa', 002);
        insert {self.tb_name} values('backbery', 'canada', 003);
        drop procedure if exists {self.pro_name};
        create definer = {self.user_name} procedure {self.pro_name}
        as
                company_name varchar(100);
                company_loc varchar(100);
                company_no integer;
        begin
                declare c1_all cursor is
                        select name, loc, no from {self.tb_name} order \
                        by 1, 2, 3;
                if not c1_all%isopen then open c1_all;
                end if;
                loop
                        fetch c1_all into company_name, company_loc, \
                        company_no;
                        exit when c1_all%notfound;
                        raise notice '% : % : %', company_name, company_loc, \
                        company_no;
                end loop;
                if c1_all%isopen then
                        close c1_all;
                end if;
        end;'''
        self.log.info(sql)
        res = sh_primary.execut_db_sql(sql, dbname=self.db_name)
        self.log.info(res)
        self.assertIn('CREATE ROLE', res, '建表失败')
        self.assertIn('CREATE TABLE', res, '建表失败')
        self.assertIn('CREATE PROCEDURE', res, '建表失败')

        text = '-----step5:执行basebackup;expect:成功-----'
        self.log.info(text)
        cmd = f"source {macro.DB_ENV_PATH};" \
              f"gs_basebackup -D {self.back_path} -Fp -X stream " \
              f"-p {self.user_node.db_port} -l gauss_0033.bak -v " \
              f"-U {self.user_node.ssh_user} -w"
        self.log.info(cmd)
        res = self.common.get_sh_result(self.user_node, cmd)
        self.assertIn('base backup successfully', res, '备份失败')

        self.log.info('-----stop原数据库-----')
        stop_res = sh_primary.stop_db_instance()
        self.assertIn('server stopped', stop_res, '建表失败')

        self.log.info('-----start备份数据库并查询状态-----')
        start_res = sh_primary.start_db_instance(dn_path=self.back_path)
        self.assertIn('server started', start_res, '建表失败')

        self.log.info('-----build备机-----')
        res1 = self.sh_sta1.build_standby(mode='')
        self.assertIn('server started', res1, '备1build失败')
        res2 = self.sh_sta2.build_standby(mode='')
        self.assertIn('server started', res2, '备2build失败')

        self.log.info('-----查询数据库状态-----')
        cmd = f"source {macro.DB_ENV_PATH};" \
              f"gs_ctl query -D {self.back_path}"
        self.log.info(cmd)
        status = self.common.get_sh_result(self.user_node, cmd)
        self.assertTrue('Normal' or 'Degraded' in status, '数据库状态异常')

        text = '-----step6:查询表;expect:成功-----'
        self.log.info(text)
        sql_cmd = f"select * from {self.tb_name};"
        self.log.info(sql_cmd)
        res = sh_primary.execut_db_sql(sql_cmd, dbname=self.db_name)
        self.log.info(res)
        rows, _ = self.common.parse_sql_query_res(res)
        expect = [['macrosoft', 'usa', '1'], ['oracle', 'usa', '2'],
                  ['backbery', 'canada', '3']]
        self.assertEqual(rows, expect, '执行失败' + text)

        text = '-----step7:查询存储过程;expect:成功-----'
        self.log.info(text)
        sql_cmd = f"show create procedure {self.pro_name};"
        self.log.info(sql_cmd)
        res = sh_primary.execut_db_sql(sql_cmd, dbname=self.db_name)
        self.log.info(res)
        self.assertIn('CREATE DEFINER = user_backup_case0033 PROCEDURE', res,
                      '执行失败' + text)

    def tearDown(self):
        self.log.info('-----step8:清理环境; expect:成功-----')
        stop_res = sh_primary.stop_db_instance(dn_path=self.back_path)
        start_res = sh_primary.start_db_instance()
        res1 = self.sh_sta1.build_standby(mode='')
        res2 = self.sh_sta2.build_standby(mode='')
        status = sh_primary.get_db_cluster_status(param='detail')
        self.log.info(status)
        check_cmd = f'rm -rf {self.back_path};' \
                    f'if [ -d {self.back_path} ]; ' \
                    f'then echo "exists"; else echo "not exists"; fi'
        self.log.info(check_cmd)
        res = self.common.get_sh_result(self.user_node, check_cmd)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"drop user if exists {self.user_name};"
        self.log.info(sql_cmd)
        sql_res = sh_primary.execut_db_sql(sql_cmd, dbname='postgres')
        self.log.info(sql_res)
        self.assertIn('server stopped', stop_res, '数据库停止失败')
        self.assertIn('server started', start_res, '主机启动失败')
        self.assertIn('server started', res1, '备1build失败')
        self.assertIn('server started', res2, '备2build失败')
        self.assertTrue('Normal' or 'Degraded' in status, '数据库状态异常')
        self.assertEqual('not exists', res, '文件删除失败')
        self.assertIn('DROP DATABASE', sql_res, '数据库创建失败')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
